import { nextTick, reactive, ref } from 'vue'
import Danmaku from '@nplayer/danmaku'
import { playerInfoStore } from '@renderer/store/playerInfo'
import { playersetStore } from '@renderer/store/playerSet'
import { storeToRefs } from 'pinia'
import NPlayer, { EVENT } from 'nplayer'
const { ipcRenderer } = require('electron')
import _ from 'lodash'
export default () => {
    let player
    const danmakuSource: any = ref([])
    const playerInfo = playerInfoStore()
    const playerSet = playersetStore()
    const { historyPlaylist } = storeToRefs(playerInfo)
    const { colorfulBarrage, memoryPlayback, autoPlay, autoNext } = storeToRefs(playerSet)
    const playVideoId = ref('')
    // 弹幕配置
    const danmakuOptions = {
        autoInsert: true,
        items: [] as any
    }
    // 右键截图
    const Screenshot = {
        html: '截图',
        click(player) {
            const canvas = document.createElement('canvas')
            canvas.width = player.video.videoWidth
            canvas.height = player.video.videoHeight
            canvas.getContext('2d')!.drawImage(player.video, 0, 0, canvas.width, canvas.height)
            canvas.toBlob((blob) => {
                let dataURL = URL.createObjectURL(blob!)
                const link = document.createElement('a')
                link.href = dataURL
                link.download = 'NPlayer.png'
                link.style.display = 'none'
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                URL.revokeObjectURL(dataURL)
            })
        }
    }
    const mountLocalBarrage = {
        html: '本地弹幕',
        click() {
            mountBarrage()
        }
    }
    const Mirroring: any = {
        type: 'switch',
        html: '视频镜像',
        checked: false,
        init(player) {
            player.video.classList.remove('nplayer_video-mirroring')
        },
        change(value, player) {
            player.video.classList.toggle('nplayer_video-mirroring', value)
        }
    }
    // 播放器配置
    const options = reactive({
        container: '#player',
        title: '标题',
        src: '',
        height: "100vh",
        contextMenus: [Screenshot, 'loop', 'pip', mountLocalBarrage],
        plugins: [new Danmaku(danmakuOptions)],
        autoSeekTime: 0,
        settings: [Mirroring, 'speed']
    })

    // 挂载弹幕
    const mountBarrage = () => {
        // 选取本地文件
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.xml';
        fileInput.addEventListener('change', (event) => {
            const file = (event.target as HTMLInputElement).files![0];
            const reader = new FileReader();
            reader.onload = (e) => {
                const xmlData = e.target!.result as string;
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(xmlData, "application/xml");
                const danmakuElements = xmlDoc.querySelectorAll('d');
                const danmuArr: any = [];
                danmakuElements.forEach((danmakuElement) => {
                    const attributes = danmakuElement.getAttribute('p')!.split(',');
                    const timeInSeconds = parseFloat(attributes[0]);
                    const danmakuText = danmakuElement.textContent;
                    // 直接使用展开语法来创建对象，更简洁高效
                    danmuArr.push({
                        time: Math.round(timeInSeconds * 1),
                        text: danmakuText,
                        color: colorfulBarrage.value ? "#" + attributes[6] : "#FFFFFF",
                        type: attributes[1] == '1' ? 'scroll' : attributes[1] == '5' ? 'bottom' : 'top',
                    });
                });

                // 使用requestAnimationFrame替代setTimeout，优化渲染时机
                requestAnimationFrame(() => {
                    // danmuArr 按时间排序
                    danmuArr.sort((a, b) => a.time - b.time);
                    danmakuSource.value = danmuArr;
                    if (player) {
                        player.danmaku.resetItems(danmuArr);
                    } else {
                        danmakuOptions.items = danmuArr;
                    }
                });
            }
            reader.readAsText(file);
        });
        fileInput.click();
    }
    let playingNow:any = reactive({})
    // 初始化视频
    const startPlayer = (item: any, $emit: Function) => {
        playingNow = item
        if (playVideoId.value == item.uid) return
        playVideoId.value = item.uid
        options.src = item.path
        options.title = item.name
        // 从 historyPlaylist 获取时间
        const historyItem = historyPlaylist.value.find((video) => video.uid === item.uid);
        if (historyItem && memoryPlayback.value) {
            options.autoSeekTime = historyItem.currentTime
        }

        nextTick(() => {
            if (player) {
                // player.dispose()
                player.updateOptions({
                    src: item.path,
                    title: item.name,
                })
                if (autoPlay.value) player.play()
            } else {
                player = new NPlayer(options)
                player.mount('#player')
                if (autoPlay.value) player.play()
                player.on(EVENT.TIME_UPDATE, _.throttle(() => {
                    playingNow.currentTime = Math.floor(player.currentTime)
                    const index = historyPlaylist.value.findIndex((video) => video.uid === playingNow.uid)
                    if (index !== -1) {
                        // 存在，更新当前时间
                        historyPlaylist.value[index].currentTime = playingNow.currentTime
                    } else {
                        // 获取视频总时长
                        const duration = Math.round(player.duration)
                        playingNow.duration = duration
                        // 不存在，添加到数组中，判断是否超过36个，超过则删除最后一个
                        if (historyPlaylist.value.length >= 36) {
                            historyPlaylist.value.pop()
                        }
                        historyPlaylist.value.unshift(playingNow)
                    }
                    ipcRenderer.send('update-storage', JSON.stringify(playerInfo.$state), 'playerInfo')
                }, 1000))
                player.on(EVENT.ENDED, () => {
                    if (player.loop || !autoNext.value) return
                    $emit('nextVideo')
                })
            }
        })
    }

    return {
        startPlayer
    }
}